package com.com.effectivejava.serializability.util;

import com.com.effectivejava.objectcreation.StaticClassIntialization;

import java.io.*;

/**
 * Created by pankaj on 7/19/14.
 */
public class ObjectStream {

    PrintStream out;

    public ObjectStream() {
    }

    public <T extends Serializable> byte[] serialize(T serialize){
        ByteArrayOutputStream baos = null;
        ObjectOutputStream oos = null;
        try{
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(serialize);
        }catch (IOException e){
            out.println(StackTrace.asString(e));

        }finally {
            Cleanup.closeQuietly(oos);
            Cleanup.closeQuietly(baos);
        }

        return baos.toByteArray();
    }

    public <T extends Serializable> T deSerialize(byte [] data){
        ObjectInputStream ois = null;
        ByteArrayInputStream bias = null;
        T t = null;

        try{
            bias = new ByteArrayInputStream(data);
            ois = new ObjectInputStream(bias);
            t = (T) ois.readObject();

        }catch (Exception e){
            out.println(StackTrace.asString(e));

        }finally {
            Cleanup.closeQuietly(ois);
            Cleanup.closeQuietly(bias);
        }
        return t;
    }

}
